package com.xj.service.service.impl;

import com.xj.service.domain.Product;
import com.xj.service.fegin.ProductService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xj.service.domain.Order;
import com.xj.service.mapper.OrderMapper;
import com.xj.service.service.OrderService;

import java.util.Date;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService{
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Order createOrder(Integer pid) {
        //调用商品微服务,查询商品信息
        Product product = productService.findById(pid);
        if (product.getId() == -1) {
            Order order = new Order();
            order.setPname("下单失败");
            return order;
        }
        //下单(创建订单)
        Order order = new Order();
        order.setUserid(1);
        order.setOrderno(new Date().getTime());
        order.setProductid(pid);
        order.setTotalprice(product.getPrice());
        order.setNum(1);
        orderMapper.insert(order);
        //3 扣库存
        productService.reduceInventory(pid, order.getNum());
        //下单成功之后,将消息放到mq中
//        rocketMQTemplate.convertAndSend("order-topic", order);
        return order;
    }
}
